<template>
  <a-spin :spinning="spinning">
    <div class="main-box">
      <div class="tree-box">
        <a-card :body-style="{ padding: '10px'}">
          <div class="tree">
            <a-tree :tree-data="treeData" :auto-expand-parent="autoExpandParent" :default-selected-keys="selectedKey" :expanded-keys="expandedKeys" @select="onSelect"
              @expand="onExpand">
              <template slot="custom" slot-scope="item">
                <div :class="[selectedKey == item.key ? 'ant-tree-node-selected' : '']">
                  <span>{{ item.title }} {{ item.userTotal ? ` (${item.userTotal}人)`:'' }}</span>
                </div>
              </template>
            </a-tree>
          </div>
        </a-card>
      </div>
      <div class="right-box">
        <a-card :body-style="{ 'min-height': 'calc(100vh - 100px)' }">
          <div style="height: 60px">
            <a-input-search placeholder="搜索员工" v-model="searchParam.realname" style="width: 200px; " @search="userSearch" />
            <a-button type="primary" style="float: right" @click="addOrEdit('newAdd')">新建</a-button>
          </div>
          <a-table ref="table" size="middle" :scroll="{ x: true, y: 'calc(100vh - 320px)' }" rowKey="id" :columns="tableColumn" :dataSource="dataSource"
            :pagination="false" :loading="tableLoading" :rowSelection="{
              columnTitle:' ',
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }" class="j-table-force-nowrap" @change="handleTableChange">
            <span slot="actions" slot-scope="text, record">
              <a-button @click=authorize(record) type="link" style="padding:0">角色授权</a-button>
              <a-dropdown>
                <a class="ant-dropdown-link" style="margin-left:10px">
                  更多
                </a>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a-button type="link" @click="addOrEdit('edit',record)">编辑</a-button>
                  </a-menu-item>
                  <a-menu-item>
                    <a-button type="link" @click="deleteItem('singleDelete',record)">删除</a-button>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </span>
          </a-table>
          <!-- 全选/分页 -->
          <div class="uni-card" style="padding-bottom:0">
            <div style="display: inline-block">
              <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
              <span class='btn-text' style="margin:0 24px" @click="batchAction">角色授权</span>
              <span class='btn-text' style="margin:0 24px" @click="deleteItem('batchDelete')">删除</span>
              <span style="margin-left: 8px">
                {{ `已选 ${selectedRowKeys.length}/${total} 项` }} <span class='btn-text' @click="clearArr" style="margin: 0 10px">清空</span>
              </span>
            </div>
            <div style="display: inline-block; float: right">
              <a-pagination :total="total" v-model="current" size="small" :page-size-options="pagination.pageSizeOptions" :page-size="pagination.pageSize"
                @change="onChangePage" @showSizeChange="onShowSizeChange" show-quick-jumper show-size-changer />
            </div>
          </div>
        </a-card>
      </div>
    </div>
    <!-- 单独授权 -->
    <a-drawer title="角色授权" placement="right" :closable="true" :visible="drawerVisible" @close="onDrawerClose" :width="500" style="height: 100%;">
      <p>请勾选授权角色</p>
      <div class='userBox'>
        <a-checkbox-group v-model="checkedList">
          <div class="check-item" v-for="(item, index) in roleList" :key="index">
            <a-checkbox :value="item.id"> {{ item.roleName }} </a-checkbox>
          </div>
        </a-checkbox-group>
      </div>
      <div :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }">
        <a-button :style="{ marginRight: '10px' }" type="primary" @click="submitRoles"> 确定 </a-button>
        <a-button :style="{ marginRight: '8px' }" @click="onDrawerClose"> 取消 </a-button>
      </div>
    </a-drawer>
    <!-- 批量授权 -->
    <a-modal v-model="handleVisible" @ok="handleOk" @cancel="handleCancel" :closable="false" :confirmLoading="confirmLoading">
      <div style="display:flex">
        <a-icon type="question-circle" style="font-size:24px;margin-right:24px;color:#ff943e" />
        <div>
          <p>您正在为<span v-for="(row, i) in selectedRows" :key="`${i}${row.id}`"
              v-show="i < 4">{{ `${row.realname}${i === 3 || i === selectedRows.length -1 ? '' : '、'}` }}</span><span v-show="selectedRows.length > 4">...</span><span
              style="color:#1890FF">{{selectedRows.length}}人</span>进行角色授权;</p>
          <p>授权后会给被授权人开通相应权限；</p>
          <p>确定授权吗？</p>
        </div>
      </div>
      <div style="display:flex;align-items:center">
        <span>角色：</span>
        <a-select mode="multiple" placeholder="请选择" allowClear style="flex:1" v-model="selectedRoles">
          <a-select-option v-for="option in roleList" :key="option.id" :value="option.id">{{ option.roleName }}</a-select-option>
        </a-select>
      </div>
    </a-modal>
    <!-- 新建编辑 弹框 -->
    <a-modal v-model="addDialog" :bodyStyle="{ padding: '32px 32px 24px', boxSizing: 'border-box' }" :maskClosable="false" :title="actionType=='newAdd'?'新建用户':'编辑用户'"
      @cancel="cancelAdd">
      <a-form-model ref="addForm" :model="newAddForm" :rules="addRules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="账号：" prop="username">
          <a-input v-model="newAddForm.username" placeholder="请输入" :maxLength="15" @blur="checkUser(newAddForm.username)" />
        </a-form-model-item>
        <a-form-model-item label="姓名：" prop="realname">
          <a-input placeholder="请输入" v-model="newAddForm.realname" :maxLength="15" />
        </a-form-model-item>
        <a-form-model-item label="部门：" prop="selecteddeparts">
          <j-select-depart v-model="newAddForm.selecteddeparts" :multi="true" :backDepart="true" :treeOpera="true">></j-select-depart>
        </a-form-model-item>
        <a-form-model-item label="角色分配：" prop="selectedroles">
          <j-multi-select-tag v-model="newAddForm.selectedroles" :options="rolesOptions" placeholder="请选择">
          </j-multi-select-tag>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button @click="cancelAdd">取消</a-button>
        <a-button type="primary" :loading="accloading" @click="saveAcction('addForm')">确定</a-button>
      </template>
    </a-modal>
  </a-spin>
</template>

<script>
import {
  queryTreeByKeyWord,
  dingtalkSaveUsers,
  queryPageListByDepartId,
  roleGetRoles,
  userEditUserRole,
  refreshSyncOrganizationQuart,
  batchAuthRole,
} from '@/api/authorityManagement'
import SettingCost from './modules/settingCost'
import { mapState } from 'vuex'
import { queryall, addUser, editUser, queryUserRole } from '@/api/api'
import {
  postAction,
  getAction,
  putAction,
  deleteAction,
  httpAction,
  fromDataPostAction,
  fromDataPost,
} from '@/api/manage'
export default {
  name: 'AuthorityManagementUserManager',
  components: {
    SettingCost,
  },
  data() {
    return {
      handleVisible: false,
      selectedRoles: undefined,
      spinning: false,
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      selectedKey: [],

      pagination: {
        pageSize: 10,
        current: 1,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total) => `共${total}条`,
      },
      searchParam: {
        realname: '',
        pageSize: 10,
        pageNo: 1,
      },
      dataSource: [],
      tableLoading: false,
      selectedRowKeys: [],
      selectedRows: [],
      tableColumn: [
        {
          title: '姓名',
          width: 150,
          key: 'realname',
          ellipsis: true,
          dataIndex: 'realname',
          customRender: (text, record, index) => {
            if (!text) return '-'
            return (
              <div style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap;">
                <a-tooltip placement="top">
                  <template slot="title">
                    <span>{text}</span>
                  </template>
                  {text}
                </a-tooltip>
              </div>
            )
          },
        },
        {
          title: '登录账号',
          width: 150,
          key: 'username',
          ellipsis: true,
          dataIndex: 'username',
          customRender: (text, record, index) => {
            if (!text) return '-'
            return (
              <div
                class="ant-table-row-cell-ellipsis"
                style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap;max-width:150px"
              >
                <a-tooltip placement="top">
                  <template slot="title">{text}</template>
                  {text}
                </a-tooltip>
              </div>
            )
          },
        },
        {
          title: '角色',
          width: 350,
          key: 'roleList',
          dataIndex: 'roleList',
          ellipsis: true,
          customRender: (text, record, index) => {
            if (!text) return '-'
            return (
              <div class="ant-table-row-cell-ellipsis" style="max-width:250px">
                <a-tooltip placement="topLeft">
                  <template slot="title">
                    <span>{text.map((i) => i.roleName).join('、')}</span>
                  </template>
                  {text.map((i) => i.roleName).join('、')}
                </a-tooltip>
              </div>
            )
          },
        },
        {
          title: '操作',
          key: 'handle',
          width: 150,
          algin: 'left',
          scopedSlots: {
            customRender: 'actions',
          },
        },
      ],
      roleList: [],
      drawerVisible: false,
      checkedList: [], //角色授权当前角色
      roleCurrentId: '', //角色授权当前用户id
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      current: 1,
      total: 0,
      confirmLoading: false,

      addDialog: false,
      actionType: '',
      labelCol: { span: 4 },
      wrapperCol: { span: 17 },
      newAddForm: {
        username: '',
        realname: '',
        selectedroles: '',
        selecteddeparts: '',
      },
      addRules: {
        username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        realname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        selecteddeparts: [{ required: true, message: '请选择部门', trigger: 'change' }],
      },
      accloading: false,
      rolesOptions: [],
      itemInfo: {},
    }
  },
  async created() {
    this.getTree()
    this.getRoles()
    this.initRoleList()
  },
  computed: {
    ...mapState({
      collapsed: (state) => state.user.collapsed,
    }),
  },
  methods: {
    deleteItem(deleteType, record) {
      let deleteUrl = '/sys/permission/permissionDelete'
      let obj = {}
      if (deleteType == 'batchDelete') {
        if (this.selectedRowKeys.length == 0) {
          this.$antdMessage.warning('请先选择数据')
          return
        }
        deleteUrl = '/sys/permission/permissionDeleteBatch'
        obj.ids = this.selectedRowKeys.join(',')
      } else {
        obj.id = record.id
      }
      let that = this
      that.$antdConfirm({
        title: '确定删除吗?',
        onOk() {
          deleteAction(deleteUrl, obj).then((res) => {
            if (res.code == 200) {
              that.$antdMessage.success('删除成功！')
              that.selectedRowKeys = []
              that.selectedRows = []
              that.listIndeterminate = false
              that.listCheckAll = false
              that.pagination.current = 1
              that.current = 1
              that.getList()
            } else {
              that.$antdMessage.warning(res.message)
            }
          })
        },
        onCancel() {},
      })
    },
    //初始化角色字典
    initRoleList() {
      queryall().then((res) => {
        if (res.success) {
          this.rolesOptions = res.result.map((item, index, arr) => {
            let c = { label: item.roleName, value: item.id }
            return c
          })
        }
      })
    },
    userSearch() {
      this.pagination.current = 1
      this.current = 1
      this.getList()
    },
    //左侧部门树结构
    async getTree() {
      try {
        this.spinning = true
        const res = await queryTreeByKeyWord()
        this.treeData = this.addSlots(res.result.departList)
        if (res.result.departList && res.result.departList.length) {
          this.$set(this.expandedKeys, 0, res.result.departList[0].key)
          if (this.selectedKey.length === 0) {
            this.selectedKey = [res.result.departList[0].key]
          }
          this.getList()
        }
        this.spinning = false
      } catch (e) {
        this.spinning = false
        console.log(e)
      }
    },
    addSlots(data) {
      let arr = []
      for (let i = 0; i < data.length; i++) {
        arr[i] = data[i]
        arr[i].scopedSlots = { title: 'custom' }
        if (data[i].children && data[i].children) {
          arr[i].children = this.addSlots(data[i].children)
        }
      }
      return arr
    },
    onSelect(e) {
      this.selectedKey = e
      this.pagination.current = 1
      this.current = 1
      this.getList()
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },

    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.searchParam.pageNo = pagination.current
      this.searchParam.pageSize = pagination.pageSize
      this.getList('page')
    },
    async getList(type = '') {
      try {
        this.tableLoading = true
        if (type !== 'page') {
          // this.searchParam.pageSize = 10
          this.searchParam.pageNo = 1
        }
        const res = await queryPageListByDepartId(
          Object.assign({}, this.searchParam, { departId: this.selectedKey[0] })
        )
        this.dataSource = res.result.records
        this.checkBoxStatus()
        this.pagination.total = res.result.total
        this.total = res.result.total

        this.tableLoading = false
      } catch (e) {
        this.tableLoading = false
        console.log(e)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.checkBoxStatus()
    },
    // 全选begin
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.dataSource) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            console.log('each != item.id:', each != item.id)
            return each != item.id
          })
          this.selectedRowKeys.push(item.id)
          this.selectedRows = this.selectedRows.filter((each) => {
            return each.id != item.id
          })
          this.selectedRows.push(item)
        }
      } else {
        for (let item of this.dataSource) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            console.log('each != item.id:', each != item.id)
            return each != item.id
          })
          this.selectedRows = this.selectedRows.filter((each) => {
            return each.id != item.id
          })
        }
      }
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.dataSource) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        console.log('第一个参数是；', checkValue)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 批量授权
    batchAction() {
      let that = this
      if (that.selectedRowKeys.length > 0) {
        this.handleVisible = true
      } else {
        that.$antdMessage.info('请先选择数据')
      }
    },
    async handleOk() {
      if (this.selectedRoles) {
        let userIds = this.selectedRowKeys.join(',')
        let roleIds = this.selectedRoles.join(',')
        try {
          this.confirmLoading = true
          const res = await batchAuthRole({ userIds, roleIds })
          this.$antdMessage.success(res.message)
          this.selectedRowKeys = []
          this.selectedRows = []
          this.listIndeterminate = false
          this.listCheckAll = false
          this.handleCancel()
          this.getList('page')
          this.confirmLoading = false
        } catch (e) {
          this.confirmLoading = false
        }
      } else {
        this.$antdMessage.warning('请选择角色！')
      }
    },
    handleCancel() {
      this.handleVisible = false
      this.selectedRoles = undefined
    },
    /* 清除 */
    clearArr() {
      this.selectedRowKeys = []
      this.checkBoxStatus()
    },
    // 分页
    onChangePage(current, pageSize) {
      this.current = current
      this.pagination.pageSize = pageSize
      this.searchParam.pageNo = current
      this.searchParam.pageSize = pageSize
      this.getList('page')
    },
    onShowSizeChange(current, pageSize) {
      this.current = current
      this.pagination.pageSize = pageSize
      this.searchParam.pageNo = current
      this.searchParam.pageSize = pageSize
      this.getList('page')
    },
    // 全选end
    authorize(data) {
      console.log('要生了个；', data)
      this.checkedList = data.roleList.map((i) => i.id)
      this.roleCurrentId = data.id
      this.drawerVisible = true
      this.getRoles()
    },
    async getRoles() {
      try {
        const res = await roleGetRoles()
        this.roleList = res.result
      } catch (e) {
        console.log(e)
      }
    },
    async submitRoles() {
      try {
        const obj = {
          userId: this.roleCurrentId,
          roleIds: this.checkedList.join(','),
        }
        const res = await userEditUserRole(obj)
        if (res.success) {
          this.$notification.success({ message: '系统提示', description: res.message })
          this.drawerVisible = false
          this.getList('page')
        } else {
          this.$notification.error({ message: '系统提示', description: res.message })
        }
      } catch (e) {
        console.log(e)
      }
    },
    onDrawerClose() {
      this.drawerVisible = false
    },
    // 点击 modal的取消按钮
    cancelAdd() {
      this.addDialog = false
      this.$refs.addForm.resetFields()
      this.accloading = false
    },
    checkUser(val) {
      let obj = {
        name: val,
      }
      if (this.actionType == 'newAdd') {
        obj.flag = '1'
      } else {
        obj.flag = '2'
        obj.id = this.itemInfo.id
      }
      postAction('/sys/permission/checkDuplicateNames', obj).then((res) => {
        if (res.code == 500) {
          this.$antdMessage.warning(res.message)
          this.newAddForm.username = ''
        }
      })
    },
    addOrEdit(actionType, row) {
      this.actionType = actionType

      if (actionType == 'edit') {
        this.itemInfo = row
        this.newAddForm = Object.assign({}, { selectedroles: '', selecteddeparts: '' }, row)
        this.getUserRoles(row.id)
        this.getUserDeparts(row.id)
      }
      this.addDialog = true
    },
    getUserRoles(userid) {
      queryUserRole({ userid: userid }).then((res) => {
        if (res.success) {
          this.newAddForm.selectedroles = res.result.join(',')
        }
      })
    },
    getUserDeparts(userid) {
      let that = this
      getAction('/sys/user/userDepartList', { userId: userid }).then((res) => {
        if (res.success) {
          let selectDepartKeys = []
          for (let i = 0; i < res.result.length; i++) {
            selectDepartKeys.push(res.result[i].key)
          }
          that.newAddForm.selecteddeparts = selectDepartKeys.join(',')
        }
      })
    },
    //点击 新增||编辑仓库 的保存按钮
    saveAcction(addForm) {
      this.$refs[addForm].validate((valid) => {
        if (valid) {
          this.accloading = true
          let param = {
            ...this.newAddForm,
          }
          let requestUrl = '/sys/permission/permissionAddUser'
          let requestType = postAction
          if (this.actionType == 'edit') {
            requestUrl = '/sys/permission/permissionEdit'
            requestType = putAction
            param.id = this.itemInfo.id
          }
          requestType(requestUrl, param).then((res) => {
            console.log(res, 'res add edit')
            if (res.success) {
              this.$antdMessage.success(res.message)
              this.accloading = false
              this.cancelAdd()
              this.pagination.current = 1
              this.current = 1
              this.getList()
            } else {
              this.accloading = false
              this.$antdMessage.warning(res.message)
            }
          })
        } else {
          return false
        }
      })
    },
  },
}
</script>
<style>
.ant-drawer-body {
  height: 100% !important;
}
</style>
<style lang="less" scoped>
.main-box {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  .tree-box {
    width: 320px;
    .tree {
      height: calc(100vh - 118px);
      overflow-y: scroll;
    }
  }
  .right-box {
    margin-left: 20px;
    flex: 1;
  }
}
.tree-item-box {
  // width: 100%;
  // display: flex;
  // flex-flow: row nowrap;
  // justify-content: space-between;
  // align-items: center;
}
.ant-tree-node-selected {
  background-color: #bae7ff;
}

.check-item {
  margin-top: 10px;
}
.userBox {
  padding-bottom: 60px;
}
</style>